package com.zingrow.common.authority;

import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.zingrow.web.user.model.User;

public class AuthorityAnnotationInterceptor extends HandlerInterceptorAdapter {

    final Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public boolean preHandle(HttpServletRequest httpRequest, HttpServletResponse httpResponse, Object handler)
            throws Exception {
        HttpSession session = httpRequest.getSession();
        HandlerMethod handler2 = (HandlerMethod) handler;
        AuthorityAnnotation authorityAnnotation = handler2.getMethodAnnotation(AuthorityAnnotation.class);

        if (null == authorityAnnotation) {
            // 没有声明权限,放行
            return true;
        }
        User user = (User) session.getAttribute("userinfo");
        boolean aflag = false;

        for (AuthorityTypeEnum at : authorityAnnotation.AuthorityTypes()) {
            if (AuthorityHelper.hasAuthority(at.getIndex(), user.getUserType() + "")) {
                aflag = true;
                break;
            }
        }

        if (false == aflag) {
            if (authorityAnnotation.resultType() == HttpResultTypeEnum.page) {
                // 传统的登录页面
                String path = httpRequest.getScheme() + "://" + httpRequest.getServerName() + ":"
                        + httpRequest.getServerPort() + httpRequest.getContextPath() + "/";
                httpResponse.sendRedirect(path + "index.jsp");
            } else if (authorityAnnotation.resultType() == HttpResultTypeEnum.json) {
                // ajax类型的登录提示
                httpResponse.setCharacterEncoding("utf-8");
                httpResponse.setContentType("text/html;charset=UTF-8");
                OutputStream out = httpResponse.getOutputStream();
                PrintWriter pw = new PrintWriter(new OutputStreamWriter(out, "utf-8"));
                pw.println("{\"result\":false,\"code\":12,\"errorMessage\":\"没有权限\"}");
                pw.flush();
                pw.close();
            }
            return false;
        }
        return true;
    }

}